import socket
import datetime
import ipaddress
from binascii import *


def is_ipv4(k: str):
    """
    判断字符串是否为IPv4地址
    """
    try:
        socket.inet_pton(socket.AF_INET, k)
    except socket.error:
        return False
    return True


def is_ipv6(k: str):
    """
    判断字符串是否为IPv6地址
    """
    try:
        socket.inet_pton(socket.AF_INET6, k)
    except socket.error:
        return False
    return True


def timeA_to_timeB(k: str, format_A='(0)%b %d, %Y %H:%M:%S.000000000 %Z', format_B='%Y-%m-%d %H:%M:%S'):
    """
    将A格式时间，转为B格式时间
    """
    return time.strftime(format_B, time.strftime(format_A, k))


def datetimeA_to_datetimeB(k: str, datetime_A='%Y-%m-%d %H:%M:%S (utc)', datetime_B='%Y%m%d%H%M%Sz'):
    """
    将A格式时间，转为B格式时间
    """
    return datetime.datetime.strptime(k, datetime_A).__format__(datetime_B)


def format_ipv6(k: str):
    """格式化IPv6地址"""
    if (is_ipv6(k)):
        k = ipaddress.IPv6Address(k)
    return k
